/**
 * @file models/brinson.js
 * @author
 */

import api from '../api';

export default {
	namespace: 'brinsonResult',
	state: {
		names:[],
		weight:[],
		rights:[],
		table:[],
		org:{}
	},
	subscriptions : {
		setup({dispatch, history}) {
			history.listen(({ pathname, query }) => {
				// 没有参数时，向后端请求数据，并且改变query
				if( pathname === '/achievement/equity/brinson' ){
					dispatch({type: 'whetherRequest',payload:query})
				}
			})
		}
	},
	effects : {

		* whetherRequest({
				payload
			}, { put,select}) {
				yield put({type:'clearState'})
				const {
					lPortId,
					timeRange,
					cBenchCode,
					indunum,
					beginDate,
					endDate
				}=payload
				if(lPortId||timeRange||cBenchCode||indunum){
					if(lPortId&&cBenchCode&&indunum&&((timeRange=='0'&&beginDate&&endDate)||(timeRange!='0'))){
						yield put({
							type:'query',
							payload
						})
					}
				}
		},

		* query({payload}, {call, put,select}){

			const brinson = yield call(api.getBrinsonList, payload)

			if(brinson.data){
				const {list,total}=brinson.data
				const table=list,names=[],weight=[],rights=[]
				table.map((item,i)=>{
					names.push(item.indunumname)
					weight.push(item.weight_difference.replace("%","")/1)
					rights.push(item.contribution_difference.replace("%","")/1)
				})
				if(total&&total.indunum){
					table.unshift(total)
				}
				yield put({type:'clearState'})

				yield put({
					type: 'querySuccess',
					payload: {
						names,
						weight,
						rights,
						table,
						org:total
					}
				});
			}

		},
	},
	reducers : {
		setState(state, {payload}) {
			return {
				...state,
				...payload
			}
		},

		clearState(state) {
      return{
				names:[],
				weight:[],
				rights:[],
				table:[],
				org:{}
			}
    },

		querySuccess(state, {payload}) {
			return {
				...state,
				...payload
			}
		}
	}
};
